﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using PepsiCo.Business;

namespace PepsiCo.UI
{
    public partial class EditUser : BasePage
    {
        #region Properties
        int UserID
        {
            get
            {
                if (ViewState["UserID"] == null) return 0;
                return (int)ViewState["UserID"];
            }
            set
            {
                ViewState["UserID"] = value;
            }
        }
        string Action
        {
            get
            {
                if (ViewState["Action"] == null) return string.Empty;
                return (string)ViewState["Action"];
            }
            set
            {
                ViewState["Action"] = value;
            }
        }
        #endregion
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            Action = GetQueryString("action");
            switch (Action)
            {
                case "add":
                    if (!AllowCreateUser())
                    {
                        RedirectToPage(AccessDeniedURL);
                    }
                    pnlPassword.Visible = true;
                    txtUserName.Enabled = true;
                    break;
                case "edit":
                    if (!AllowEditUser())
                    {
                        RedirectToPage(AccessDeniedURL);
                    }
                    pnlPassword.Visible = false;
                    txtUserName.Enabled = false;
                    break;
                default:
                    RedirectToPage(AccessDeniedURL);
                    break;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                int userID = 0;
                int.TryParse(Request.QueryString["UserID"], out userID);
                UserID = userID;
                BindUnit();
                BindDataGroup();
                BindDataRole();
                SetData();
                if (!AllowGrantPrivileges())
                {
                    pnlGrantPrivileges.Enabled = false;
                }
            }
        }

        private void BindUnit()
        {
            if (CurUser.Name.Equals(Constants.AdminRootAccount, StringComparison.CurrentCultureIgnoreCase))
            {
                ddlStaff.DataSource = DB.pepsi_Staffs.OrderBy(p => p.StaffCode);
            }
            else
            {
                ddlStaff.DataSource = DB.sp_pepsi_StaffGetByUnit(CurUser.UnitID);
            }
            ddlStaff.DataValueField = "StaffID";
            ddlStaff.DataTextField = "StaffCode";
            ddlStaff.DataBind();
        }

        private void SetData()
        {
            var objUser = DB.pepsi_Users.FirstOrDefault(p => p.UserID == UserID);
            if (objUser != null)
            {
                txtUserName.Text = objUser.Name;
                txtEmail.Text = objUser.Email;
                ddlStaff.SelectedValue = objUser.StaffID.ToString();
                var staff = DB.pepsi_Staffs.FirstOrDefault(p => p.StaffID == objUser.StaffID);
                if (staff != null)
                {
                    txtStaffLevel.Text = staff.StaffLevel.ToString();
                    txtStaffName.Text = staff.StaffName;
                    txtUnitName.Text = staff.pepsi_Unit.Name;
                    txtStaffType.Text = staff.pepsi_StaffType.StaffTypeName;
                }
            }
        }

        private void CheckExistUser()
        {
            if (DB.pepsi_Users.Any(p => p.Name == txtUserName.Text.Trim()))
                throw new Exception("This user name already exists!");
        }

        private void CheckUserStaff(int userID, Guid? staffID)
        {
            if(DB.pepsi_Users.Any(p=>p.UserID != userID && p.StaffID == staffID))
                throw new Exception("The staff been already another user!");
        }
       
        protected void btnOk_Click(object sender, EventArgs e)
        {
            try
            {
                pepsi_User objUser = null;
                if (Action == "add")
                {
                    CheckExistUser();
                    objUser = new pepsi_User();
                }
                if (Action == "edit")
                {
                    objUser = DB.pepsi_Users.FirstOrDefault(p => p.UserID == UserID);
                }
                if (objUser != null)
                {
                    objUser.Email = txtEmail.Text.Trim();
                    objUser.StaffID = new Guid(ddlStaff.SelectedValue);
                    objUser.UnitID = DB.pepsi_Staffs.FirstOrDefault(p => p.StaffID == new Guid(ddlStaff.SelectedValue)).UnitID;
                    if (Action == "add")
                    {
                        objUser.Name = txtUserName.Text.Trim();
                        objUser.Pwd = txtPassword.Text.Trim().ToMD5UTF8Encryption();
                        objUser.DateCreated = DateTime.Now;
                        DB.pepsi_Users.InsertOnSubmit(objUser);
                    }
                    CheckUserStaff(objUser.UserID, objUser.StaffID);
                    //Edit Groups and roles
                    if (AllowGrantPrivileges())
                    {
                        //Delete old group and role
                        DB.pepsi_User_Groups.DeleteAllOnSubmit(DB.pepsi_User_Groups.Where(p => p.pepsi_User == objUser));
                        DB.pepsi_User_Roles.DeleteAllOnSubmit(DB.pepsi_User_Roles.Where(p => p.pepsi_User == objUser));
                        //ReAdd group and role
                        foreach (RepeaterItem item in rptGroup.Items)
                        {
                            CheckBox chk = (CheckBox)item.FindControl("chkCheck");
                            if (chk.Checked)
                            {
                                HiddenField hdf = (HiddenField)item.FindControl("hdfGroup");
                                var newObj = new pepsi_User_Group()
                                {
                                    pepsi_User = objUser,
                                    GroupID = int.Parse(hdf.Value)
                                };
                                DB.pepsi_User_Groups.InsertOnSubmit(newObj);
                            }
                        }
                        foreach (RepeaterItem item in rptRole.Items)
                        {
                            CheckBox chk = (CheckBox)item.FindControl("chkCheck");
                            if (chk.Checked)
                            {
                                HiddenField hdf = (HiddenField)item.FindControl("hdfRole");
                                var newObj = new pepsi_User_Role()
                                {
                                    pepsi_User = objUser,
                                    RoleID = int.Parse(hdf.Value)
                                };
                                DB.pepsi_User_Roles.InsertOnSubmit(newObj);
                            }
                        }
                    }
                    DB.SubmitChanges();
                    RedirectToPage(ReturnURL);
                }
            }
            catch (Exception ex)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "alert(\"" + ex.Message + "\");", true);
            }
        }

        private void BindDataRole()
        {
            rptRole.DataSource =
            DB.pepsi_Roles.Select(p => new
            {
                p.RoleId,
                p.RoleName,
                p.Description,
                Checked = p.pepsi_User_Roles.Any(q => q.UserID == UserID)
            });
            rptRole.DataBind();
        }

        private void BindDataGroup()
        {
            rptGroup.DataSource =
                   DB.pepsi_Groups.Select(p => new
                   {
                       p.GroupID,
                       p.GroupName,
                       p.Description,
                       Checked = p.pepsi_User_Groups.Any(q => q.UserID == UserID)
                   });
            rptGroup.DataBind();
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            RedirectToPage(ReturnURL);
        }
    }
}